﻿using Microsoft.AspNetCore.Mvc;
using System.Reflection;

namespace Luka;

/// <summary>
/// 特性扩展
/// </summary>
[NotScanned]
public static class AttributeExtensions
{
    /// <summary>
    /// 返回某个特性(ActionContext)
    /// </summary>
    /// <returns></returns>
    public static TAttribute? GetAttribute<TAttribute>(this ActionContext context) where TAttribute : Attribute
    {
        var attr = context.ActionDescriptor.EndpointMetadata.FirstOrDefault(it => it.GetType().Equals(typeof(TAttribute)));
        if (attr != null && attr is TAttribute myAttribute)
        {
            return myAttribute;
        }
        return default;
    }

    /// <summary>
    /// 获取方法特性(MethodInfo)
    /// </summary>
    /// <returns></returns>
    public static TAttribute? GetAttribute<TAttribute>(this MethodInfo method) where TAttribute : Attribute
    {
        var attribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType().Equals(typeof(TAttribute)));
        if (attribute != null && attribute is TAttribute myAttribute)
        {
            return myAttribute;
        }
        return default;
    }

    /// <summary>
    /// 是否包含某个特性(ActionContext)
    /// </summary>
    /// <returns></returns>
    public static bool HasAttribute<TAttribute>(this ActionContext context) where TAttribute : Attribute, new()
    {
        return context.ActionDescriptor.EndpointMetadata.Any(it => it.GetType().Equals(typeof(TAttribute)));
    }

    /// <summary>
    /// 是否包含某个特性(MethodInfo)
    /// </summary>
    /// <returns></returns>
    public static bool HasAttribute<TAttribute>(this MethodInfo method) where TAttribute : Attribute
    {
        return method.IsDefined(typeof(TAttribute), false);
    }

    /// <summary>
    /// 是否包含某个特性(Type)
    /// </summary>
    /// <returns></returns>
    public static bool HasAttribute<TAttribute>(this Type type) where TAttribute : Attribute, new()
    {
        return type.IsDefined(typeof(TAttribute), false);
    }
}